<template>
  <div class="home">
    <header class="header-container">
      <home-header />
    </header>
    <main class="main-container">
      <home-swiper :list="swipers" />
      <van-skeleton v-if="groups.length === 0" title :row="4" />
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <div v-for="(group, index) in groups">
          <h4 class="group-time" v-if="group.date">
            <span>{{ group.date | filterTime }}</span
            ><i></i>
          </h4>
          <ul>
            <li v-for="news in group.list" :key="news.id">
              <router-link :to="{ path: `/detail/${news.id}` }">
                <news-item :title="news.title" :image="news.images ? news.images[0] : ''" :hint="news.hint" />
              </router-link>
            </li>
          </ul>
        </div>
      </van-list>
    </main>
  </div>
</template>

<script>
import { API_LATEST, API_BEFORE } from '@/api'
import HomeHeader from '@/components/HomeHeader'
import HomeSwiper from '@/components/HomeSwiper'
import NewsItem from '@/components/NewsItem'
import { formatTime } from '@/utils/util'

export default {
  name: 'Home',
  components: {
    HomeHeader,
    HomeSwiper,
    NewsItem
  },
  data() {
    return {
      swipers: [],
      groups: [],
      loading: false,
      finished: false,
      date: formatTime(new Date())
    }
  },
  methods: {
    async onLoad() {
      if (this.swipers.length) {
        // 获取历史记录
        const res = await API_BEFORE(this.date)
        this.date = res.date
        this.groups.push({
          date: res.date,
          list: res.stories || []
        })
        if (!res.stories || res.length === 0) {
          this.finished = true
        }
      } else {
        // 获取最新消息
        const res = await API_LATEST()
        this.groups.push({
          date: undefined,
          list: res.stories || []
        })
        this.swipers = res.top_stories
      }
      // 加载状态结束
      this.loading = false
    }
  },
  filters: {
    // 格式化时间
    filterTime(time) {
      let month = time.substr(4, 2),
        day = time.substr(6)
      return month + ' 月 ' + day + ' 日'
    }
  }
}
</script>

<style lang="less" scoped>
.home {
  width: 100%;
  height: 100vh;

  .header-container {
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 60px;
  }

  .main-container {
    overflow-y: auto;
    box-sizing: border-box;
    width: 100%;
    height: calc(100vh - 60px);
    background: #fff;

    .group-time {
      display: flex;
      align-items: center;
      margin: 0;
      padding: 10px 0;
      font-size: 13px;
      color: #999;
      text-indent: 15px;
      i {
        display: block;
        flex: 1;
        height: 1px;
        background: #ededed;
        margin-left: 10px;
      }
    }
  }
}
</style>
